import axios, { AxiosInstance } from 'axios'
import { Toast } from 'antd-mobile'
import * as MD5 from 'js-md5'
import * as SHA1 from 'js-sha1'
export { msg, NotBean, NotCart, NotOrder, NotColl } from './global'
const URI = 'http://api.icotc.com/index/'

// const URI = 'http://192.168.213.91/Business/v1/'

// 加密
const time = Date.now()

const instance: AxiosInstance = axios.create({
    baseURL: URI,
    timeout: 10000,
    headers: {
        'X-Token': SHA1(MD5((time * 5 + 1).toString())),
        'X-Time': time
    }
})
instance.interceptors.request.use(function (config: any) {
    // config.data = { data: SHA1(config.data) }
    return config
})
instance.interceptors.response.use(function (res: any) {
    if (res.data.code === 200 && res.status === 200) {
        return res.data.data
    } else {
        const data = res.data
        if (data) {
            Toast.info(data.msg, 2)
        } else {
            Toast.info('网络堵塞, 请稍后再试', 2)
            Toast.hide()
        }
        return Promise.reject(res.data)
    }
})

export const post = function (uri: string, params?: object): any {
    return instance.post(`${URI}${uri}`, {
        ...params
    })
}

export const formatPriceStr = (str: string) => {
    // let priceStr = ''
    let pointIdx = str.indexOf('.')
    let integer = ''
    let decimal = ''

    if (pointIdx > -1) {
        integer = str.substr(0, pointIdx)
        decimal = str.substr(pointIdx)
    } else {
        integer = str
    }

    var num = 0
    var arr = []
    for (var i = integer.length - 1; i >= 0; i -= 1) {
        arr.push(integer[i])
        if ((num + 1) % 3 === 0 && i !== 0) {
            arr.push(',')
        }
        num += 1
    }

    return arr.reverse().join('') + decimal
}

export const showPhone = (val: string) => {
    return val.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3')
}